﻿<?php

$db_user_name = 'maxzzz';
$db_user_pass = 'maxaaa';
$db_name = 'mail';
$host_name = 'localhost';

// Users
$domain    = "uar.net";
$cat_id    = 3;
$amount    = 10;
$expire    = "2012-01-01";
$status    = 1;
$uname     = "uar";
$password  = "Vl19Pv61";
$firstname = "Vladimir";
$lastname  = "Konko";
$orgname   = "IP Depo Corp.";
$email     = "Vladimir.Konko@ipdepo.com";
$notes     = "";

//Проверка входных данных
    if( $domain == "" || $uname == "" || $password == "" || $firstname == "" || $expire == "" ||
        ( $cat_id < 1 || $cat_id > 3 ) || ( $status < 0 || $status > 1 ) || !is_numeric($amount) )
        exit( "Ошибка входных данных.\n" );
        
// Подключение к БД
    set_exception_handler('exception_handler');
    
    $db = new PDO("mysql:host=$host_name;dbname=$db_name", $db_user_name, $db_user_pass);
    if( $db->exec('SET CHARACTER SET CP1251') === false )
        exit( "Ошибка открытия базы данных.\n" );

// Проверка присутствия в БД домена
    $recset = $db->query("SELECT `user_id` FROM `users` WHERE `domain`=".$db->quote($domain));
    if(($row = $recset->fetch(PDO::FETCH_ASSOC)) !== false )
        exit("Данный домен уже зарегистрирован.\n");

// Добавляем пользователя
    $sqls = "INSERT INTO `users` SET ".
            "`domain`=".$db->quote($domain).", ".
            "`cat_id`=".$cat_id.", ".
            "`amount`=".$amount.", ".
            "`status`=".$status.", ".
            "`expire`=".$db->quote($expire).", ".
            "`uname`=".$db->quote($uname).", ".
            "`password`=".$db->quote(md5($password)).", ".
            "`firstname`=".$db->quote($firstname).", ".
            "`lastname`=".$db->quote($lastname).", ".
            "`orgname`=".$db->quote($orgname).", ".
            "`email`=".$db->quote($email).", ".
            "`notes`=".$db->quote($notes);

    if( $db->exec( $sqls ) === false )
        exit( "Ошибка добавления нового пользователя.\n");
        
    $recset = $db->query("SELECT `user_id` FROM `users` WHERE `domain`=".$db->quote($domain));
    $row = $recset->fetch(PDO::FETCH_ASSOC);
    $user_id = $row['user_id'];

// Добавляем в config_files
    $fname = array( "black-relnames", "white-from", "white-relnames", "own-relays", 
                    "rcpt-action", "white-subnets", "options" );
    
    for( $i=0; $i<count($fname); $i++ ) {
        $sqls = "INSERT INTO `config_files` SET ".
                "`user_id`=".$user_id.", `name`=".$db->quote($fname[$i]).", `sync`=0";

        if( $db->exec( $sqls ) === false )
            exit( "Ошибка добавления в config_files для ".$fname[$i].".\n");
    }
    $recset->closeCursor();
    
// Добавляем в reloads
    $sqls = "INSERT INTO `reloads` SET `user_id`=".$user_id;

    if( $db->exec( $sqls ) === false )
        exit( "Ошибка добавления в reloads\n");

// Добавляем в options
    $opts = array( 'use_default_lists', 'header_test', 'neighbouring', 
                'default_action', 'spam_house', 'reject_message' );
                
    $upds  = array('use_default_lists'=>'');
    $sqlin = $db->quote('use_default_lists'); 
    
    for( $i=1; $i<count($opts); $i++) {
        $upds[$opts[$i]] = '';
        $sqlin = $sqlin.', '.$db->quote($opts[$i]);
    }
                    
    $sqls = "SELECT d.name, t.default FROM entities_description AS d LEFT JOIN entities_templates AS t ".
            "ON t.cat_id=".$cat_id." AND t.entity_id=d.entity_id WHERE d.name IN ( ".$sqlin." )";
            
    $recset = $db->query($sqls);
    while($row = $recset->fetch(PDO::FETCH_ASSOC)) 
        $upds[$row['name']] = $row['default'];
    
    list($upds['use_default_lists'],) = explode('|',$upds['use_default_lists']);
    list($upds['header_test'],) = explode('|',$upds['header_test']);
    list($upds['neighbouring'],) = explode('|',$upds['neighbouring']);
    
    $recset->closeCursor();
    
//    print_r( $upds );
    for( $i=0; $i<count($opts); $i++) {
        $sqls = "INSERT INTO `options` SET user_id=".$user_id.", `name`=".$db->quote($opts[$i]).
                ", `value`=".$db->quote($upds[$opts[$i]]);
//        print_r( $sqls );
        if( $db->exec( $sqls ) === false )
            exit( "Ошибка добавления в options\n");        
    }
    
    echo "Пользователь ".$uname." успешно добавлен.\n";
    
exit(0);

    function exception_handler($exception) {
        echo "Непредвиденная ситуация: ".$exception->getMessage()."\n";
        exit(1);
    }

?>
